﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using Sherwood.Content.Contracts;
using Sherwood.Content.Tests;

namespace Sherwood.Samples.SearchClient
{
    /// <summary>
    /// Interaction logic for SubmitRecordWindow.xaml
    /// </summary>
    public partial class SubmitRecordWindow : Window
    {
        private readonly UpdateServiceClient _updateServiceClient;

        public SubmitRecordWindow()
        {
            InitializeComponent();

            _updateServiceClient = new UpdateServiceClient("http://content.sherwood.local:57712/UpdateService.svc");
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            var request = new updateRecordsRequest();
            request.client = new client { id = "SampleClient", signature = "1234" };
            request.content = new updateRecordsRequestType.contentLocalType();
            request.content.record = new List<record>();

            var record = new record();
            record.referenceId = id.Text;
            record.title = title.Text;
            record.description = description.Text;
            record.culture = Thread.CurrentThread.CurrentUICulture.Name;
            record.updateMode = "CreateOrUpdate";
            
            record.meta = new List<record.metaLocalType>();

            var meta = new record.metaLocalType();
            meta.handler = "ArticleMeta";
            meta.updateMode = "CreateOrUpdate";
            using (var xmlWriter = meta.Untyped.CreateWriter())
            {
                xmlWriter.WriteStartElement("body");
                xmlWriter.WriteCData(body.Text);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteElementString("author", author.Text);
                if (publishDate.SelectedDate != null)
                {
                    var date = XmlConvert.ToString(publishDate.SelectedDate.Value, XmlDateTimeSerializationMode.Utc);
                    xmlWriter.WriteElementString("publishDate", date);
                }
            }
            record.meta.Add(meta);
            
            request.content.record.Add(record);

            request.Sign(SampleClient.PrivateKey);

            _updateServiceClient.UpdateRecords(request);
        }
    }
}
